package com.mdxx.xczd.service;

import android.app.ActivityManager;
import android.app.Notification;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.google.gson.Gson;
import com.mdxx.xczd.R;
import com.mdxx.xczd.aidl.ProcessService;
import com.mdxx.xczd.app.App;
import com.mdxx.xczd.app.UrlValue;
import com.mdxx.xczd.bean.LocationAndNetWorkBean;
import com.mdxx.xczd.bean.LocationRo;
import com.mdxx.xczd.bean.LocationRo.PositionRo;
import com.mdxx.xczd.bean.MessageEvent;
import com.mdxx.xczd.bean.Point;
import com.mdxx.xczd.bean.TimeInfoBean;
import com.mdxx.xczd.db.cache.CacheDeta;
import com.mdxx.xczd.utils.FormatUtil;
import com.mdxx.xczd.utils.NetworkUtil;
import com.mdxx.xczd.utils.OkHttpManager;
import com.orhanobut.logger.Logger;
import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * @author dz 20160906
 *
 */
public class LocationService extends Service {
	private double mLatitude;
	private double mLongtitude;	
	private LocationClient mLocationClient;
	private MyLocationListener mLocationListener;
	private Point point = new Point();
	private CacheDeta cache ;
	private LocationAndNetWorkBean info1 = new LocationAndNetWorkBean();
	private TimeInfoBean realTimeInfo1 = new TimeInfoBean(); 
	private MyBinder binder;
	private MyConn conn;
	List<PositionRo> positiList = new ArrayList<>();
	@Override
	public IBinder onBind(Intent intent) {
		return binder;
	}

	@Override
	public void onCreate() {		
		super.onCreate();
		SDKInitializer.initialize(getApplicationContext());
		cache = CacheDeta.getInstance();
		initLocation();		
		binder = new MyBinder();
		if(conn==null){
			conn = new MyConn();
		}		
	}

	@Override
	@Deprecated
	public void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);
		Notification.Builder builder = new Notification.Builder(this);
		builder.setSmallIcon(R.drawable.ic_launcher);
		startForeground(250, builder.build());
		startService(new Intent(this,NotificationService.class));
		LocationService.this.bindService(new Intent(this,GuardService.class),conn, Context.BIND_IMPORTANT);
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		if (!mLocationClient.isStarted())
			mLocationClient.start();
		return super.onStartCommand(intent, flags, startId);
	}

	@Override
	public void onDestroy() {		
		super.onDestroy();
		mLocationClient.stop();
	}

	class MyBinder extends ProcessService.Stub{

		@Override
		public String getServiceName() throws RemoteException {
			return "I am FirstService";
		}
	}

	class  MyConn implements ServiceConnection {

		@Override
		public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
			ActivityManager activityManager = (ActivityManager) LocationService.this
					.getSystemService(Context.ACTIVITY_SERVICE);
		}

		@Override
		public void onServiceDisconnected(ComponentName componentName) {
			/*Toast.makeText(LocationService.this,"LocationService被杀死",Toast.LENGTH_SHORT).show();*/
			LocationService.this.startService(new Intent(LocationService.this,GuardService.class));
			LocationService.this.bindService(new Intent(LocationService.this,GuardService.class),conn, Context.BIND_IMPORTANT);
		}
	}

	private void initLocation(){
		mLocationClient = new LocationClient(this);
		mLocationListener = new MyLocationListener();
		mLocationClient.registerLocationListener(mLocationListener);
		LocationClientOption option = new LocationClientOption();
		option.setCoorType("bd09ll");
		option.setIsNeedAddress(true);
		option.setOpenGps(true);
		option.setScanSpan(1000);
		option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
		mLocationClient.setLocOption(option);
	}

	private class MyLocationListener implements BDLocationListener{
		public void onReceiveLocation(BDLocation location) {
			if (App.USERID == null || App.USERID.equals("")) return ;
			mLatitude = location.getLatitude();
			mLongtitude = location.getLongitude();
			point.setLatitude(mLatitude);
			point.setLongitude(mLongtitude);
			App.radius = location.getRadius();
			App.addrstr = location.getAddrStr();
			refreshRealTimeInfo(location);
			if(mLatitude != 4.9e-324){
			App.mPoint.setLatitude(mLatitude);
			App.mPoint.setLongitude(mLongtitude);
			if(positiList.size() <= 10){
				positiList.add(getPositionRo(location));
			}else{
				/*String strTaskNum = App.taskBean == null ? " " : App.taskBean.taskNum;*/

				sortList(positiList);
				LocationRo locationRo = new LocationRo();
				locationRo.setEmpNum(App.USERID);
				locationRo.setPositons(positiList.subList(0, 1));
				/*locationRo.setTaskNum(strTaskNum);*/
				if(App.taskBean == null){
					locationRo.setTaskNum("");
				}else{
					locationRo.setTaskNum(App.taskBean.taskNum);
				}
				submitLocationTest(locationRo);
				positiList.clear();
			}
			//				if(AppConfig.taskBean == null)  return;
			//				submitLocation(point);	
			EventBus.getDefault().post(new MessageEvent(null, null, 3));
						}
		}

	}

	private void submitLocationTest(LocationRo locationRo) {
		Gson gson=new Gson();
		final String coordinate=gson.toJson(locationRo);
		Logger.d("coordinate="+coordinate);
		OkHttpManager.HeaderParam[] headerparams = {new OkHttpManager.HeaderParam("empNum", App.USERID),new OkHttpManager.HeaderParam("imei",NetworkUtil.getAndroid_id())};
		OkHttpManager.Param[] params = {new OkHttpManager.Param("params", coordinate)};
		try {
			OkHttpManager.postAsyn(UrlValue.location, headerparams, params,
					new OkHttpManager.ResultCallback<String>(){
				@Override
				public void onError(Exception e) {
					EventBus.getDefault().post(new MessageEvent(null, null, 8));
					cache.locationData(coordinate);			
				}

				@Override
				public void onResponse(String response) {
					Logger.d("response="+response);
					JSONObject jb_RESULT;
					String code = null;
					try {
						jb_RESULT = new JSONObject(response);
						code = jb_RESULT.optString("code");
						if("4".equals(code)){
							EventBus.getDefault().post(new MessageEvent(null, null, 5));						
						}else if("5".equals(code)){
							EventBus.getDefault().post(new MessageEvent(null, null, 11));
						}else if("6".equals(code)){
							EventBus.getDefault().post(new MessageEvent(null, null, 10));
						}else{
							EventBus.getDefault().post(new MessageEvent(null, null, 7));
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
			});
		} catch (IOException e) {
			e.printStackTrace();
		}				
	}

	private void refreshRealTimeInfo(BDLocation location){
		//		realTimeInfo1.setCellID(NetworkUtil.getCId()+"");
		realTimeInfo1.setDeviceNum(NetworkUtil.getAndroid_id());
		realTimeInfo1.setCellularSignalStrength(App.dbm);
		realTimeInfo1.setLocationType(location.getLocType());
		realTimeInfo1.setPower(App.batteryLevel);
		realTimeInfo1.setNetworkStrength(NetworkUtil.getNetworkType_longcha());
		realTimeInfo1.setSatelliteNum(location.getSatelliteNumber());
		submitLocation(realTimeInfo1);
	}

	private void submitLocation(TimeInfoBean realTimeInfo1) {
		OkHttpManager.Param[] params = {
				new OkHttpManager.Param("deviceNum", realTimeInfo1.getDeviceNum()),
				new OkHttpManager.Param("power", realTimeInfo1.getPower()+""),
				new OkHttpManager.Param("cellularSignalStrength",realTimeInfo1.getCellularSignalStrength()+""),
				new OkHttpManager.Param("locationType", realTimeInfo1.getLocationType()+""),
				new OkHttpManager.Param("satelliteNum", realTimeInfo1.getSatelliteNum()+""),
				new OkHttpManager.Param("networkStrength", realTimeInfo1.getNetworkStrength()+"")

		};
		try {
			OkHttpManager.postAsyn(UrlValue.deviceInfo, null, params,
					new OkHttpManager.ResultCallback<String>(){
						@Override
						public void onError(Exception e) {}

						@Override
						public void onResponse(String response) {

						}
					});
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private PositionRo getPositionRo(BDLocation location){
		PositionRo positionRo = new PositionRo();
		positionRo.setLat(location.getLatitude());
		positionRo.setLng(location.getLongitude());
		positionRo.setTime(FormatUtil.str2Date());
		positionRo.setRadius(location.getRadius());
		return positionRo;
	}


	private void sortList(List<PositionRo> positiList){		
		Collections.sort(positiList, new Comparator<PositionRo>() {
			@Override
			public int compare(PositionRo o1, PositionRo o2) {				
				return (int)(o1.getRadius() - o2.getRadius());
			}
		});		
	}	
}


